<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      canvas {
        border: 1px solid #000;
        margin: 100px auto;
      }
    </style>
  </head>
  <body>
    <canvas id="canvas" width="400" height="400"></canvas>

    <script>
      const canvas = document.querySelector("#canvas");
      const ctx = canvas.getContext("2d");

      const radius = canvas.width / 2;

      const drawClock = () => {
        ctx.clearRect(0, 0, 400, 400);

        const now = new Date();
        const hour = now.getHours();
        const minutes = now.getMinutes();
        const seconds = now.getSeconds();

        // 画表盘
        ctx.beginPath();
        ctx.arc(radius, radius, radius - 10, 0, 2 * Math.PI);
        ctx.strokeStyle = "#000";
        ctx.lineWidth = 5;
        ctx.stroke();
        ctx.closePath();

        drawZhen(
          (((hour % 12) * 30 + minutes * 0.5 - 90) / 360) * 2 * Math.PI,
          100,
          "#000",
          8
        );
        drawZhen(
          ((minutes * 6 + seconds * 0.1 - 90) / 360) * 2 * Math.PI,
          130,
          "#ccc",
          5
        );
        drawZhen(((seconds * 6 - 90) / 360) * 2 * Math.PI, 170, "red", 3);

        for (let i = 0; i < 60; i++) {
          ctx.save();
          ctx.translate(radius, radius);
          ctx.translate(
            (radius - 10) * Math.sin(((6 * i) / 180) * Math.PI),
            -(radius - 10) * Math.cos(((6 * i) / 180) * Math.PI)
          );
          if (i % 5) {
            ctx.fillRect(-3, -3, 6, 6);
          } else {
            ctx.fillRect(-6, -6, 12, 12);
          }

          ctx.restore();
        }
      };

      const drawZhen = (deg, length, color, width) => {
        // 画时针
        ctx.save(); // save是保存当前状态
        ctx.translate(radius, radius);
        ctx.rotate(deg);
        ctx.beginPath();
        ctx.moveTo(0, 0);
        ctx.lineTo(length, 0);
        ctx.strokeStyle = color;
        ctx.lineWidth = width;
        ctx.stroke();
        ctx.closePath();
        ctx.restore(); // restore回到前一次save之前的状态
      };

      drawClock();

      setInterval(() => {
        drawClock();
      }, 1000);
    </script>
  </body>
</html>
